package com.nowoe.data.parse;

import com.nowoe.data.config.Configuration;
import com.nowoe.data.constant.SqlCommandTypeEnum;
import com.nowoe.data.statement.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author 倚栏听风 2023/9/14 16:18
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream resourceStream) throws DocumentException {
        Document document = new SAXReader().read(resourceStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        parseByType(rootElement, namespace, SqlCommandTypeEnum.SELECT);
        parseByType(rootElement, namespace, SqlCommandTypeEnum.INSERT);
        parseByType(rootElement, namespace, SqlCommandTypeEnum.UPDATE);
        parseByType(rootElement, namespace, SqlCommandTypeEnum.DELETE);
    }

    private void parseByType(Element rootElement, String namespace, SqlCommandTypeEnum type) {
        List<Node> selectNodes = rootElement.selectNodes("//" + type.getSqlType());
        for (Node selectNode : selectNodes) {
            Element el = (Element) selectNode;
            String id = el.attributeValue("id");
            String parameterType = el.attributeValue("parameterType");
            String resultType = el.attributeValue("resultType");
            String sql = el.getTextTrim();
            //封装mapperStatement
            MapperStatement mapperStatement = new MapperStatement();
            String statementId = namespace + "." + id;
            mapperStatement.setStatementId(statementId);
            mapperStatement.setParameterType(parameterType);
            mapperStatement.setResultType(resultType);
            mapperStatement.setSql(sql);
            mapperStatement.setSqlCommandType(type);
            configuration.getMapperStatementMap().put(statementId, mapperStatement);
        }
    }
}
